<template>
  <view class="page_root" data-page-name="绩效列表" data-page-identification="x_i54b6a2d6g">
    <!-- UNI_APP_EXEGESIS_START NAVIGATION_TEMPLATE UNI_APP_EXEGESIS_END -->
    <!-- begin vid_ot0untjlou 自定义模板_404xgtfx4c -->
    <!-- 编辑评分 -->
    <u-toast ref="uToast1" />
    <u-modal
      v-model="editVisible"
      title="编辑"
      @confirm="handleSubmit"
      @cancel="handleCancelEdit"
      show-cancel-button="true"
      :async-close="true"
      ref="editModalRef"
    >
      <u-form :model="currentEditData" ref="addRef" label-position="top">
        <u-form-item label="主管评分">
          <u-input
            border
            v-model="currentEditData.managerFraction"
            placeholder="请输入"
            clickable
            type="number"
          />
        </u-form-item>
        <u-form-item label="评分备注">
          <u-input
            border
            v-model="currentEditData.managerFractionDescription"
            placeholder="请输入"
            clickable
            type="textarea"
          />
        </u-form-item>
      </u-form>
    </u-modal>
    <!-- 编辑评分 -->
    <u-mask :show="ygState.tableLoading">
      <view class="warp">
        <view class="rect" @tap.stop>加载中....</view>
      </view>
    </u-mask>
    <u-navbar
      title="员工绩效"
      title-color="#fff"
      back-icon-color="#fff"
      :is-fixed="true"
      :border-bottom="false"
      title-width="250"
    >
    </u-navbar>
    <view class="bot-bg"></view>
    <view class="top-title">主管评分系统</view>
    <view class="content">
      <view class="dropdown-card">
        <van-dropdown-menu style="width: 200rpx">
          <van-dropdown-item
            v-model="ygState.filter.month"
            :title="ygState.filter.month"
            @change="getData"
            ref="searchTimeRef"
          >
            <van-date-picker
              @confirm="onConfirmSearchTime($event)"
              @cancel="cancelSearchTime"
              v-model="ygState.dayMonth"
              :columns-type="['year', 'month']"
          /></van-dropdown-item>
        </van-dropdown-menu>
      </view>
      <view class="main">
        <view v-for="(item, index) in ygState.tableData" :key="item.id" class="people-item">
          <view class="people-top">
            <view class="people-top-left">
              <view class="people-name">{{ item.userName }}</view>
              <view class="people-departmentName">{{ item.departmentName }}</view>
              <view :class="['people-status', getStatus(item.ratingStatus)]">{{
                item.ratingStatus
              }}</view>
            </view>
            <view class="people-top-right" @click="handleEdit(item)"></view>
          </view>
          <view class="leader-score">
            <text class="leader-label">主管评分：</text>
            <text class="leader-value">{{ item.managerFraction }}</text>
          </view>
          <view class="description-label"> 主管评分备注： </view>
          <text class="description-value">{{ item.managerFractionDescription }}</text>
        </view>
      </view>
    </view>
    <view class="footer-bar">
      <van-button
        type="primary"
        :loading="submitLoading"
        @click="handleSubmitScore"
        :style="{
          backgroundImage: 'linear-gradient(-75deg, #82B0FF 0%, #3366FF 74%)',
          border: 'none',
          color: '#fff',
        }"
      >
        {{ submitLoading ? '提交中...' : '提交评分' }}
      </van-button>
    </view>
    <!-- end vid_ot0untjlou 自定义模板_404xgtfx4c -->
  </view>
</template>
<script setup>
  import {
    ref,
    reactive,
    toRaw,
    markRaw,
    watch,
    computed,
    onBeforeMount,
    onMounted,
    onBeforeUnmount,
    onUnmounted,
    onActivated,
    onDeactivated,
    getCurrentInstance,
  } from 'vue';
  import { useRoute } from 'vue-router';
  const route = useRoute();
  import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios';
  import {
    cloneDeep,
    localGet,
    traversalTreeStructure,
    set,
    checkCaseCondition,
    throttle,
    merge,
    debounce,
    getGridStyle,
    getCellRenderAble,
    formulaStrategy,
    getApplicationId,
    getComponentParamsValue,
    get as lodashGet,
  } from '@/utils/index';
  import {
    isEqual,
    isNullOrEmpty,
    isEmptyArr,
    isArray,
    isEmpty,
    isNullOrUnDef,
    isContained,
  } from '@/utils/is';
  import { CovertOptions, getChartsDataSourceConvert } from '@/utils/chart';
  import {
    propertyFormatByNumber,
    propertyFormatByPercentage,
    propertyFormatByDate,
    parseSubFromDataList,
  } from '@/utils/format';
  import { checkCommonCondition, getResultByCurrentCommonCondition } from '@/utils/formCondition';
  import { FormFormat } from '@/utils/formFormat';
  import { customAddWaterMarkFunc, generateWaterMarkText } from '@/utils/addWaterMark';
  import dayjs from 'dayjs';
  import hashSum from 'hash-sum';
  /*** UNI_APP_EXEGESIS ***
  import { handleRedirect, permission, parseJson } from '@/utils/common';
  import { onPullDownRefresh, onLoad, onReady, onShow, onHide, onPageScroll, onUnload } from '@dcloudio/uni-app';
  import { BroadcastMessage } from '@/utils/BroadcastMessage';
  import { sendToken } from "@/hooks/useIframeToken";
  *** UNI_APP_EXEGESIS ***/

  // ---------------------------- 属性定义 ----------------------------
  const sourceId = 'page3000001244';

  // 获取传入的流程ID和组件参数
  const props = defineProps({
    processInstanceId: {
      type: [String, Number, Boolean],
      default: undefined,
    },
    hideNav: {
      type: [Boolean],
      default: undefined,
    },
  });

  // 组件参数默认值
  const componentParamsDefaultProps = {};

  // 是否显示菜单按钮
  const isMenuIconShow = false;
  // NAVIGATION_MENU
  const handleShowNavigation = () => {};

  let isProcessState = ref(false);

  const setTimeOutList = [];

  const vid_ot0untjlou_props = reactive({
    code: '',
  });

  // ============================ 属性定义 ============================

  // ---------------------------- 元素数据引用 ----------------------------
  // 组件 自定义模板_404xgtfx4c ref 的引用
  const vid_ot0untjlou_ref = ref(null);
  // 动态key的map
  const fieldTypeMap = {};
  // 动态key的map
  const refMap = { vid_ot0untjlou_ref };

  const showState = reactive({
    vid_ot0untjlou_visible: true,
  });
  // ============================ 元素数据引用 ============================

  // ---------------------------- 数据 ----------------------------

  // ============================ 数据 ============================

  // ---------------------------- 方法 ----------------------------
  // ---------------------------- 页面数据 ----------------------------

  // ============================ 页面数据 ============================

  // ---------------------------- 数据字典 ----------------------------

  // ============================ 数据字典 ============================

  // ---------------------------- 响应 ----------------------------

  // ============================ 响应 ============================

  // ---------------------------- 函数 ----------------------------

  // 自定义函数 返回上一页
  const customFunction_goBack_evgcaukmqx = (params) => {
    uni.navigateBack();
  };

  // ============================ 函数 ============================

  // ---------------------------- 页面参数 ----------------------------

  const pageParameter_state = reactive({
    processInstanceId: undefined,
  });

  // ============================ 页面参数 ============================

  // ---------------------------- 组件事件处理方法 ----------------------------

  // ============================ 组件事件处理方法 ============================

  // ============================ 方法 ============================

  // ---------------------------- 生命周期 ----------------------------
  /*** UNI_APP_EXEGESIS ***
      // 获取上一层传递的数据
      const workflowChannel = new BroadcastMessage('WORKFLOW');
      workflowChannel.publish({ status: 'Ready' });
      workflowChannel.subscribe((data) => {
        if (data) {
          isProcessState.value = (window.self !== window.parent && data.type === 'hideHeader');
        }
      });
      *** UNI_APP_EXEGESIS ***/

  const pageScrollTop = ref(0);

  // *** PREVIEW_EXEGESIS ***
  onMounted(() => {
    setPageParams(route.query);
    // 设置表单的rule
    try {
    } catch {
      // do nothing
    }
  });
  // *** PREVIEW_EXEGESIS *** //

  /*** UNI_APP_EXEGESIS ***
  const routeOption = ref({})
  onLoad((option) => {
    routeOption.value = option;
  });
  onReady(() => {
    setPageParams(routeOption.value)
    // 设置表单的rule
    try{

    }catch{
        // do nothing
    }
  });
  // 图表刷新标记
  const uChartsReshowFlag = ref(false);
  onHide(() => { // 页面隐藏后标记置为false(如果不置为false无法触发图表更新)
      uChartsReshowFlag.value = false
  })
  onShow(() => {
      uChartsReshowFlag.value = true; // 页面激活后,标记置为true

      setPageParams(routeOption.value)
  })
  onPageScroll(e => {
      pageScrollTop.value = e.scrollTop
  });
  *** UNI_APP_EXEGESIS ***/

  let setPageParams = (routerParam) => {
    const pageParams = [{ dataType: 'STRING', name: 'processInstanceId' }];
    const strategyMap = {
      STRING: (param, paramValue) => {
        pageParameter_state[param.name] = paramValue;
      },
      BOOLEAN: (param, paramValue) => {
        if ('true' === (paramValue || '').toLowerCase()) {
          pageParameter_state[param.name] = true;
        } else if ('false' === (paramValue || '').toLowerCase()) {
          pageParameter_state[param.name] = false;
        } else {
          // TODO: 是否要支持toast
          console.error('参数传入错误！类型不匹配！');
        }
      },
      NUMBER: (param, paramValue) => {
        if (!isNaN(paramValue)) {
          pageParameter_state[param.name] = Number(paramValue);
        } else {
          // TODO: 是否要支持toast
          console.error('参数传入错误！类型不匹配！');
        }
      },
      ARRAY: (param, paramValue) => {
        if (isNullOrUnDef(paramValue) || !paramValue || paramValue === 'undefined') {
          // default value
          pageParameter_state[param.name] = [];
        } else if (paramValue.trim().startsWith('[') && paramValue.trim().endsWith(']')) {
          try {
            pageParameter_state[param.name] = JSON.parse(decodeURI(paramValue));
          } catch (error) {
            console.error('参数解析失败 ', error);
          }
        } else {
          console.error('参数传入错误！类型不匹配！');
        }
      },
    };
    pageParams.forEach((param) => {
      strategyMap[param.dataType](param, routerParam[param.name]);
    });
  };

  onUnmounted(() => {
    // 销毁定时器
    setTimeOutList.forEach(({ repeat, timer }) => {
      repeat ? clearInterval(timer) : clearTimeout(timer);
    });
  });

  /*** UNI_APP_EXEGESIS ***
  onPullDownRefresh(() => {
    // 下拉刷新
    setTimeout(() => {
        uni.stopPullDownRefresh()
    }, 1000)
  })
  *** UNI_APP_EXEGESIS ***/

  // ============================ 生命周期 ============================

  // ---------------------------- 数据关联处理 ----------------------------
  // ---------------------------- 组件数据同步 ----------------------------

  // ============================ 组件数据同步 ============================
  //
  // ============================ 数据关联处理 ============================

  // ---------------------- 不同组件自定义的处理逻辑 ---------------------

  // ====================== 不同组件自定义的处理逻辑 ======================

  // ================================定制化逻辑========================================
  import { showSuccessToast, showFailToast } from 'vant';
  // 按需导入 Vant 3 组件
  import {
    Form,
    Field,
    CellGroup,
    Cell,
    Picker,
    Popup,
    Uploader,
    Button,
    DatePicker,
    Dialog,
    Toast,
    Col,
    Row,
    Icon,
    Tab,
    Tabs,
    Checkbox,
    CheckboxGroup,
    PickerGroup,
    DropdownMenu,
    DropdownItem,
    ConfigProvider,
  } from 'vant';
  import 'vant/lib/index.css';
  import { nextTick } from 'vue';

  // 页面内注册 Vant 组件
  const { appContext } = getCurrentInstance();
  [
    ['van-form', Form],
    ['van-field', Field],
    ['van-cell-group', CellGroup],
    ['van-cell', Cell],
    ['van-picker', Picker],
    ['van-dialog', Dialog],
    ['van-popup', Popup],
    ['van-uploader', Uploader],
    ['van-button', Button],
    ['van-date-picker', DatePicker],
    ['van-col', Col],
    ['van-row', Row],
    ['van-icon', Icon],
    ['van-tab', Tab],
    ['van-tabs', Tabs],
    ['van-checkbox-group', CheckboxGroup],
    ['van-checkbox', Checkbox],
    ['van-picker-group', PickerGroup],
    ['van-dropdown-menu', DropdownMenu],
    ['van-dropdown-item', DropdownItem],
    ['van-config-provider', ConfigProvider],
  ].forEach(([name, comp]) => appContext.app.component(name, comp));
  onMounted(() => {
    setPageStyle('jixiao-page');
    const lastMonth = dayjs().subtract(1, 'month');
    ygState.filter.month = lastMonth.format('YYYY-MM');
    ygState.dateStr = lastMonth.format('YYYY年MM月');
    getData();
  });
  
  function setPageStyle(newClass) {
    // #ifdef H5
    // 仅在 H5 执行
    const appDiv = document.querySelector('#app');
    if (appDiv) {
      appDiv.className = '';

      // 再添加当前需要的类
      if (newClass) {
        appDiv.classList.add(newClass);
      }
    }

    const topHeader = document.querySelector('.uni-page-head');
    if (topHeader) topHeader.remove();

    const wrapper = document.querySelector('uni-page-wrapper');
    if (wrapper) wrapper.style.height = '100%';
    // #endif

    // #ifdef MP
    // 小程序端执行（如果你要做兼容逻辑，可以写这里）
    console.log('当前是小程序环境，不需要处理头部或背景');
    // #endif
  }
  const defaultDate = [
    String(new Date().getFullYear()),
    String(new Date().getMonth() + 1).padStart(2, '0'),
  ];
  const ygState = reactive({
    expandedKeys: [],
    selectedKeys: [],
    checkedKeys: [],
    searchValue: '',
    dateStr: '',
    filter: {
      userName: undefined,
      departmentName: undefined,
      month: undefined,
    },
    dayMonth: defaultDate,
    tableLoading: false,
    treeData: [],
    selected: {},
    projectNameList: [],
    tableData: [],
    peopleList: [],
    selectedRowKeys: [],
    exportScoreVisible: false,
    addOrReduceVisible: false,
    giveScoreVisible: false,
    fileList: [],
    staffType: 'DEPARTMENT',
    isTableIn: false,
    permissionVisible: false,
    permissionTitle: '',
    permissionDataSource: [],
    isEdit: false,
    editLoading: false,
    permissionLoading: false,
    tableHeight: 600,
    showColumns: [],
  });
  const searchTimeRef = ref(null);
  function onConfirmSearchTime(val) {
    console.log(val);
    const startYear = val.selectedValues[0];
    const startMonth = val.selectedValues[1];

    ygState.filter.month = `${startYear}-${startMonth}`;
    ygState.dayMonth = val.selectedValues;
    searchTimeRef.value.toggle();

    getData();
  }
  const cssMap = {
    未编辑: 'no-edit',
    未提交: 'no-submit',
    已提交: 'submited',
  };
  function getStatus(status) {
    return cssMap[status];
  }
  const isFirst = ref(true);
  function getData() {
    ygState.tableLoading = true;
    get(
      `/solution-ppm/api/v2/built-in-system-ppm/emgf/v3/list?userName=${
        ygState.filter.userName || ''
      }&month=${ygState.filter.month}&departmentName=${ygState.filter.departmentName || ''}`,
    )
      .then((data) => {
        if (data.code !== 200) {
          showFailToast(data.message);
          return;
        }
        if (isFirst.value) {
          ygState.peopleList = data.data.userMonthlyPerformanceList.map((item) => {
            return {
              label: item.userName,
              value: item.userName,
            };
          });
          ygState.departmentList = [
            ...new Map(
              data.data.userMonthlyPerformanceList.map((item) => [
                item.departmentName,
                {
                  label: item.departmentName,
                  value: item.departmentName,
                },
              ]),
            ).values(),
          ];
        }
        isFirst.value = false;
        ygState.tableData = data.data.userMonthlyPerformanceList;
      })
      .finally(() => {
        ygState.tableLoading = false;
      });
  }
  const currentEditData = ref({});
  const editVisible = ref(false);
  const editModalForm = ref(null);
  const uToast1 = ref(null);
  function handleEdit(record) {
    get(
      `/solution-ppm/api/v2/built-in-system-ppm/parameter/judge_time_control/${ygState.filter.month}/LEADER_RATING`,
    ).then((data) => {
      if (!data.data) {
        showFailToast('请在评分起止时间内操作');

        editModalForm.clearLoading();
        return;
      }
      editVisible.value = true;
    });
    currentEditData.value = { ...record };
  }
  const editModalRef = ref(null);
  async function handleSubmit(done) {
    if (
      currentEditData.value.managerFraction != 30 &&
      !currentEditData.value.managerFractionDescription
    ) {
      uToast1.value.show({
        title: '评分不等于 30 请填写评分备注',
        type: 'watn',
      });
      editModalRef.value.clearLoading();
      return;
    }

    const index = ygState.tableData.findIndex((item) => item.id === currentEditData.value.id);
    if (index !== -1) {
      ygState.tableData.splice(index, 1, { ...currentEditData.value });
    }

    try {
      const res = await put(
        `/solution-ppm/api/v2/built-in-system-ppm/emgf/v3/score_changes_batch/${ygState.filter.month}`,
        ygState.tableData,
      );

      if (res.code !== 200) {
        showFailToast(res.message);
        return;
      }

      showSuccessToast(`${res.message} 确认无误后请及时提交评分`);
      ygState.isEdit = false;
      handleCancelEdit();
      getData();
    } catch (error) {
      console.error(error);
      showFailToast('提交失败');
    }
  }
  function beforeClose() {
    if (
      currentEditData.value.managerFraction != 30 &&
      !currentEditData.value.managerFractionDescription
    ) {
      showFailToast('评分不等于 30 请填写评分备注');
      return false;
    }
  }
  function handleCancelEdit() {
    currentEditData.value = {};
    editVisible.value = false;
  }
  const submitLoading = ref(false);
  // 评分提交
  function handleSubmitScore() {
    submitLoading.value = true;
    put(`/solution-ppm/api/v2/built-in-system-ppm/emgf/v3/rating_submit/${ygState.filter.month}`)
      .then((data) => {
        if (data.code !== 200) {
          showFaileToast(data.message);
          return;
        }
        showSuccessToast(data.message);
        getData();
      })
      .finally(() => {
        submitLoading.value = false;
      });
  }
</script>
<style lang="less" scoped>
  .page_root {
    min-height: 100%;
    box-sizing: border-box;
    overflow: auto;
    background-image: url('http://10.40.0.33:9001/file-storage/540302650699495424-source.png');
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;
    position: relative;
  }
  .bot-bg {
    width: 150rpx;
    height: 200rpx;
    background-image: url('http://10.40.0.33:9001/file-storage/540307565733820416-source.png');
    background-size: cover;
    position: absolute;
    right: 110rpx;
    top: 100rpx;
    z-index: 3;
  }
  :deep(.u-navbar) {
    background-color: transparent !important;
    padding: 0 40rpx 0 0;
    border: none;
  }
  .content {
    background-image: url('http://10.40.0.33:9001/file-storage/540307095053219840-source.png');
    background-repeat: no-repeat;
    background-size: cover;
    position: relative;
    border-radius: 16px 8px 16px 16px;
    padding: 32rpx 40rpx;
  }
  .main {
    height: calc(100vh - 600rpx);
    overflow-y: auto;
  }
  .top-title {
    font-size: 36rpx;
    color: #ffffff;
    font-weight: 600;
    margin-top: 50rpx;
    padding: 0 40rpx;
    margin-bottom: 32rpx;
  }
  .dropdown-card {
    border-radius: 8rpx;
    overflow: hidden;
    margin-bottom: 32rpx;
  }
  .people-item {
    border-radius: 16rpx;
    padding: 28rpx 24rpx;
    background-image: url('http://10.40.0.33:9001/file-storage/540296109514635264-source.png');
    background-size: cover;
    margin-bottom: 32rpx;
  }
  .people-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 25rpx;
  }
  .people-top-left {
    display: flex;
    gap: 16rpx;
    align-items: center;
  }
  .people-status {
    border-radius: 8rpx;
    background: rgba(51, 102, 255, 0.3);
    font-size: 24rpx;
    color: #ffffff;
    text-align: center;

    font-weight: 400;
    padding: 4rpx 16rpx;
    display: flex;
    align-items: center;
  }
  .people-name {
    font-size: 32rpx;
    color: rgba(0, 0, 0, 0.85);
    line-height: 44rpx;
    font-weight: 600;
  }
  .people-departmentName {
    font-size: 28rpx;
    color: rgba(0, 0, 0, 0.65);
    font-weight: 400;
  }
  .people-top-right {
    background-image: url('http://10.40.0.33:9001/file-storage/540312314407368704-source.png');
    background-size: cover;
    width: 30rpx;
    height: 30rpx;
  }
  .leader-score {
    margin-bottom: 24rpx;
  }
  .leader-label {
    font-size: 24rpx;
    color: rgba(0, 0, 0, 0.45);
    font-weight: 400;
  }
  .leader-value {
    font-size: 36rpx;
    background: linear-gradient(90deg, #7353f7 6%, #3366ff 94%);
    -webkit-background-clip: text; /* 关键1：将背景裁剪到文字 */
    -webkit-text-fill-color: transparent; /* 关键2：让文字透明显示背景 */
    font-weight: 600;
  }
  .description-label {
    margin-bottom: 8rpx;

    font-size: 24rpx;
    color: rgba(0, 0, 0, 0.45);
    line-height: 32px;
    font-weight: 400;
  }
  .description-value {
    font-size: 28rpx;
    color: rgba(0, 0, 0, 0.65);
    font-weight: 400;
  }
  .no-edit {
    background: rgba(239, 122, 89, 0.6);
  }
  .no-submit {
    background: rgba(96, 165, 250, 0.6);
  }
  .submited {
    background: rgba(48, 164, 108, 0.6);
  }
  .footer-bar {
    display: flex;
    gap: 32rpx;
    padding: 16rpx;
    box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);
    margin-top: 32rpx;
    .van-button {
      flex: 1;
    }
  }
</style>
